//
//  NetworkTools.swift
//  仿一个新浪微博
//
//  Created by 孙家林 on 15/9/9.
//  Copyright © 2015年 sunjialin. All rights reserved.
//

import UIKit
import AFNetworking

/// 错误的类别标记
private let HMErrorDomainName = "com.itheima.error.network"

private enum HMNetworkError: Int {
    
    case emptyDataErroe = -1
    case emptyTokenError = -2
    
    //错误描述
    private var errorDescrption: String {
        switch self {
            case.emptyDataErroe: return "空数据"
            case.emptyTokenError : return "Token 为空"
        }
    }
    
    private func error() -> NSError {
    
        return NSError(domain: HMErrorDomainName, code: rawValue, userInfo: [HMErrorDomainName:errorDescrption])
    }
}

//网络访问方法
private enum HMNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    ///OAuth授权
    private let clientId = "2130699997"
    
    private let appSecret = "2762a40a0f40950ec1017e195c552446"
    
    ///回调地址
    let redirectUri = "http://www.baidu.com"
    
    /// 网络回调类型别名
    typealias HMNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()
    
    ///单例
    static let sharedTools:NetworkTools = {
        
        let baseURL = NSURL(string:"https://api.weibo.com/")!
        
        let tools = NetworkTools(baseURL: baseURL)
        
        ///设置数据解析数据类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/plain") as Set<NSObject>
        
        return tools
    }()
    
    //检查并生成token字典
    private func tokenDict(finished: HMNetFinishedCallBack) -> [String: AnyObject]? {
    
        ///判断token是否存在
        if UserAccount.loadAccount()?.access_token == nil {
            
            let error = HMNetworkError.emptyDataErroe.error()
            
            print(error)
            
            finished(result: nil, error: error)
            
            return nil
        }
        //生成token字典并返回
        return ["access_token":UserAccount.loadAccount()!.access_token!]
    }
    
    ///加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: HMNetFinishedCallBack){
        
        ///判断token是否存在
        // guard 是 swift 2.0 的新语法，跟 if let 刚好相反
        // let 获得的变量，后续可以直接使用，而且一定不为 nil
        guard var params = tokenDict(finished) else {
            
            // params 在此为 nil，一般直接返回
            // 提示：tokenDict已经做了token为空的错误回调
            return
        }
        
        if since_id > 0 {
        
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
        
            params["max_id"] = max_id - 1
        }
        // 代码运行至此，params 一定有值
        let urlString = "2/statuses/home_timeline.json"
        
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }
    
    ///加载用户数据
    func loadUserInfo(uid:String, finished:HMNetFinishedCallBack) {
        
         // guard 不仅可以用 let，而且可以用 var
        guard var params = tokenDict(finished) else {
            
            return
        }
        let urlString = "2/users/show.json"
        params["uid"] = uid
        
        // 发送网络请求
        // 提示：如果参数不正确，首先用 option + click 确认参数类型
        request(HMNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
        
    }
    
    ///返回OAuth 授权地址
    func oauthUrl() -> NSURL {
    
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
    
        return NSURL(string: urlString)!
    }
    
        ///加载token
    func loadAccessToken(code:String,finished:HMNetFinishedCallBack) {
    
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id": clientId,
        "client_secret": appSecret,
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": redirectUri]
        
        request(HMNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
    }
    
    // MARK: - 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    
    /// GET 请求
    ///
    /// :param: urlString URL 地址
    /// :param: params    参数字典
    /// :param: finished  完成回调
    private func request(method: HMNetworkMethod, urlString: String, params: [String: AnyObject], finished: HMNetFinishedCallBack) {
        
        //1、定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject) -> Void = { (_, JSON) -> Void in
        
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据 \(method) Request \(urlString)")
                
                finished(result: nil, error: HMNetworkError.emptyDataErroe.error())
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        // 3. 根据 method 来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
}
